<?php
namespace Modules\Box\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\ActivityOrder as Order;
use \Modules\Box\Entities\Box;

use \Modules\Order\Entities\AgentPayRecord;

use Validator;
use ThrowException;
use DB;
use Auth;
use Cache;
use Setting;

// 盲盒正式下单
class BoxOrderController extends Controller
{
    // 预览订单
    public function preview(Request $req)
    {
        $rule = [
            'room_id' => ['required'],
            'sku_index' => ['required'],
            'page_uuid' => ['required'],
            // 'room_id'
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();

        // 要求手机号
        if ( @Setting::get('sys_box')['is_need_phone'] && !$user->phone ) {
            ThrowException::RequirePhone();
        }

        $cached = Cache::get($req->page_uuid) ?: ThrowException::Conflict('页面已失效，请刷新后重试~');

        // 福袋
        $box = Box::getEntity([
            'id' => $cached['box_id']
        ]);

        $room = $box->rooms()->where('id', $req->room_id)->first() ?: ThrowException::Conflict('房间已下架~');

        // 检测是否已被开过
        $room->isSkuIndexSaleable($cached['sku_index']) || ThrowException::Conflict('来迟了，此盒被买走了~');

        // 购买总数
        $total = $req->total;

        // 整盒端
        if ($total == 0) {
            $total = $box->sku_total;
        }

        // 库存不足
        if ($total > $box->stock) {
            ThrowException::Conflict('库存不足了哦~');
        }

        if ($box->isOffStock()) {
            ThrowException::Conflict('此款已下架~');
        }

        $skuableMaps = [
            [
                'skuable' => $box,
                'total' => $total
            ]
        ];

        // DB::beginTransaction();

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        $isUseRedpack = $req->input('is_use_redpack');
        $isUseScore = $req->input('is_use_score');
        $order = Order::initWith($skuableMaps, $user, NULL, [
            'node' => $box,
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
            'is_use_score' => $isUseScore,
            'is_visible' => 0,
        ]);

        // $order->createAll();

        // DB::commit();

        // 返回订单内容
        return $order->generatePreviewResponse($user);
    }


    // 创建订单
    public function confirm(Request $req) {
    
        $rule = [
            'room_id' => ['required'],
            'sku_index' => ['required'],
            'page_uuid' => ['required'],
            // 'room_id'
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();

        // 1秒内只能调1次此api
        Auth::limitTimeBeforeProcess($user, 'create_order', 1);

        // 要求手机号
        if ( @Setting::get('sys_box')['is_need_phone'] && !$user->phone ) {
            ThrowException::RequirePhone();
        }

        $cached = Cache::get($req->page_uuid) ?: ThrowException::Conflict('页面已失效，请刷新后重试~');

        $box = Box::getEntity([
            'id' => $cached['box_id']
        ]);

        if ($box->isOffStock()) {
            ThrowException::Conflict('此款已下架~');
        }

        // 预售中不可购买
        if ($box->is_presell && $box->presell_mode == 0) {
            ThrowException::Conflict('预售中不可购买~');
        }

        $room = $box->rooms()->where('id', $req->room_id)->first() ?: ThrowException::Conflict('房间已下架~');

        // 检测是否已被开过
        $room->isSkuIndexSaleable($cached['sku_index']) || ThrowException::Conflict('来迟了，此盒被买走了~');

        // 购买总数
        $total = $req->total;

        $isWholeBox = 0;
        // 整盒端
        if ($total == 0) {
            $total = $box->sku_total;
            $isWholeBox = 1;
        }

        // 只端一个
        if ($total === 1) {
            $sku = $box->skus()->where('id', $cached['sku_id'])->first();

            if (!$sku || $sku->stock<=0) {
                ThrowException::Conflict('手慢了哦,此款已售罄~');
            }
        }

        $skuableMaps = [
            [
                'skuable' => $box,
                'total' => $total
            ]
        ];

        DB::beginTransaction();

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        $isUseRedpack = $req->input('is_use_redpack');
        $isUseScore = $req->input('is_use_score');
        $order = Order::initWith($skuableMaps, $user, NULL, [
            'node' => $box,
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
            'is_use_score' => $isUseScore,
            'is_visible' => 0,
            'options' => [
                'sku_id' => $cached['sku_id'],
                'sku_index' => $req->sku_index,
                'room_id' => $req->room_id,
                'is_whole_box' => $isWholeBox
            ]
        ]);

        // 使用免费次数兑换
        if ($req->input('is_use_free_ticket') && $total === 1) {
            $box->ticketOut($user, 1);
            $order->useFreeTicket();
        }

        $order->createAll();

        DB::commit();

        // 返回订单内容
        return $order->generateResponse($user);
    }

    // 创建订单
    public function try(Request $req, $uuid) {
        $rule = [
            'try_total' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();

        $activity = Activity::getChildrenEntity([
            'uuid' => $uuid
        ]);

        $total = $req->input('try_total') ?: 1;
        $skuableMaps = $activity->randomSku($total) ?: ThrowException::Conflict('库存不足~');

        $skus = [];
        foreach ($skuableMaps as $key => $skuableMap) {
            array_push($skus, OrderSku::initWith($skuableMap['skuable'], $skuableMap['total']));
        }

        return [
            'info' => [
                'skus' => $skus
            ]
        ];
    }
    // 正常支付开盒子 （微信小程序使用）
    // public function store(Request $req)
    // {
    //     $rule = [
    //         'room_id' => ['required'],
    //         'sku_index' => ['required'],
    //         'page_uuid' => ['required'],
    //     ];
    //     Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

    //     $user = Auth::requireLoginUser();

    //     $boxIndex = $req->sku_index;
    //     $roomId = $req->room_id;
    //     $total = intVal($req->input('total', 1));   // 购买数量

    //     // if ($total === 0) {
    //     //     ThrowException::Conflict('您好，端盒功能已暂时停用了哦~');
    //     // }

    //     $room = BoxRoom::getEntity([
    //         'id' => $roomId
    //     ]);

    //     $box = $room->box;

    //     // ThrowException::Conflict('库存不足~');

    //     // 查找sku 
    //     if ($total === 1) {
    //         // 单个开盒
    //         $pageUuid = $req->page_uuid;
    //         $cache = Cache::get($pageUuid) ?: ThrowException::Conflict('此页面已失效，请退出重新进入哦~');           

    //         $skuId = $cache['sku_id'];
    //         $sku = BoxSku::getEntity([
    //             'id' => $skuId
    //         ]);

    //         // 检测是否中隐藏款，中则替换
    //         $hiddenSku = $room->randHiddenSku();
    //         if ($hiddenSku) {
    //             $sku = $hiddenSku;
    //         }

    //         // 如果非在线开盒子，则需要进行标题、封面替换
    //         if ($sku->box->open_mode === 2) {
    //             $sku->title = $sku->box->title;
    //             $sku->number = $sku->box->number;
    //             $sku->thumb = $sku->box->thumb;
    //         }

    //         $skuableMaps = [
    //             [
    //                 'skuable' => $sku,
    //                 'total' => 1
    //             ]
    //         ];
    //     }
    //     elseif ($total === 0) {
    //         // 整盒端
    //         $skuableMaps = $box->getWholdRoomSkus() ?: ThrowException::Conflict('库存不足~');
    //     }
    //     else {
    //         // 其它数量的连抽
    //         $skuableMaps = $box->randomSkus($total) ?: ThrowException::Conflict('库存不足~');
    //     }

    //     DB::beginTransaction();

    //     $coupon = NULL;
    //     if ($req->input('coupon_id'))
    //         $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

    //     $order = BoxOrder::initWith($skuableMaps, $user, NULL, [
    //         'coupon' => $coupon,
    //         'is_use_redpack' => $req->input('is_use_redpack')
    //     ]);
    //     $order->status = 1;
    //     $order->options = [
    //         'sku_index' => $boxIndex,
    //         'box_room_id' => $roomId
    //     ];
    //     $order->is_visible = 0;

    //     // 判断是否是淘宝小程序，如果是，则应直接扣除开盒次数而不需要支付
    //     if (Auth::platformType()  ===  'ali') {
    //         $order->pay_money_price = 0;

    //         // 扣除开盒次数
    //         // 如果扣除失败则需要ThrowException

    //         $tmailProductId = $box->getTmailProductId();
    //         $remainTime = @$user->options['remain_time_map'][$tmailProductId]['remain'] ?: 0;
    //         if ($remainTime <= 0) {
    //             ThrowException::Conflict('剩余开盒次数不足，请先购买开盒次数哦~');
    //         }

    //         $options = $user->options ?: [];
    //         $options['remain_time_map'][$tmailProductId]['remain'] = $remainTime - 1;
    //         $user->update([
    //             'options' => $options
    //         ]);
    //     }

    //     $order->createAll();

    //     DB::commit();

    //     $res = [];

    //     // 如果是创建代付订单
    //     if ($req->input('create_mode') === 'agent_pay') {

    //         // 创建代付记录
    //         $agentPayRecord = AgentPayRecord::createWith($order);

    //         // 返回代付信息
    //         $res = $agentPayRecord->getInfo([
    //             'id',
    //             'uuid'
    //         ]);
    //     }
    //     else {
    //         // 返回订单内容
    //         $clientType = 'miniapp';
    //         $res = $order->generateResponse($clientType);
    //     }

    //     return $res;
    // }

    // 获取此订单可用红包
    // public function getUsableRedpack(Request $req)
    // {
    // 	$user = Auth::requireLoginUser();

    // 	$box = Box::getEntity([
    // 		'id' => $req->input('box_id')
    // 	]);

    //     $orderRate = floatVal(@Setting::get('share_setting')['redpack_order_rate'] ?: 0);
    //     $orderRate = $orderRate > 1 ? 0 : $orderRate;
    //     $calc = intVal($box->price * $orderRate);
    //     $balance = $user->asset('redpack')->balance;

    //     return [
    //     	'redpack' => $calc > $balance ? $balance : $calc
    //     ];
    // }

    // 获取订单详情
    // public function boxInfo(Request $req, $uuid)
    // {
    //     $order = BoxOrder::getEntity([
    //         'uuid' => $uuid
    //     ]);

    //     return [
    //         'info' => $order->sku,
    //         'score_reward' => @$order->options['score_reward']
    //     ];
    // }
}
